28. Exercise: Add Aligned Boxes with Click Handlers
ANDK L2 82 Click Handler HS-SC
Android Developer Documentation:
In this exercise you are going to add four more aligned boxes to your layout, modify the style, and then add a click handler to color the boxes when they are clicked. The image below shows how your layout should look.
- Add Box Two to your layout. Set the width and height to 130dp. Align it below Box One and to the left edge of the screen.
- Add boxes Three, Four, and Five below Box One and to the right of Box Two. Make them identically shaped, vertically aligned. The top of Box Three is aligned with the top of Box Two, and the bottom of Box Five is aligned with the bottom of Box Two. See the image below for reference and use a chain, additional constraints, and margins to achieve your objective.
- Add a click handler to MainActivity. Since this lesson is not about click handlers, the code is provided below for you to copy and paste.
- Update the WhiteBox style so that the boxes start out white with white font.
Click Handler Code
fun makeColored(view: View) {
when (view.id) {
// Boxes using Color class colors for background
R.id.box_one_text -> view.setBackgroundColor(Color.DKGRAY)
R.id.box_two_text -> view.setBackgroundColor(Color.GRAY)
// Boxes using Android color resources for background
R.id.box_three_text -> view.setBackgroundResource(android.R.color.holo_green_light)
R.id.box_four_text -> view.setBackgroundResource(android.R.color.holo_green_dark)
R.id.box_five_text -> view.setBackgroundResource(android.R.color.holo_green_light)
else -> view.setBackgroundColor(Color.LTGRAY)
}
}
If you get stuck, revisit the coding steps in the screencasts and use the solution code to compare your answers.
If you want to start at this step, you can download this exercise code from: Step.02-Exercise-Align-boxes-Click-handlers.
You will find plenty of //TODO comments to help you complete this exercise, and if you get stuck, go back and watch the video again.
Once you’re done, you can check your solution against the solution we’ve provided here Step.02-Solution-Align-boxes-Click-handlers or using this git diff.
Task Description:
Check the steps below as you implement them to complete this exercise.